import json
import re

from django.core.cache import cache
from django.http import JsonResponse
from django.views import View

from Lovehome_Max_Shanghai.utils.Loginmixin import LoginMixin
from django_redis import get_redis_connection

from hongt1026.verify_id import check
from six_it.models import Area, User, House, HouseImage, Order, Facility


# class AreasView(View):
#
#     def get(self, request):
#
#         # 判断是否有缓存
#         areas_list = cache.get('areas_list')
#
#         if not areas_list:
#             try:
#                 # 从数据库取出地区数据
#                 areas_model_list = Area.objects.all()
#                 # 创建地区列表
#                 areas_list = []
#                 # 向地区列表中添加数据
#                 for areas_model in areas_model_list:
#                     areas_list.append({'aid': areas_model.id,
#                                        'aname': areas_model.name})
#
#                 # 增加地区缓存数据
#                 cache.set('areas_list', areas_list, 3600 * 24 * 14)
#
#             except Exception as e:
#                 # 如果报错 返回错误原因
#                 return JsonResponse({
#                     'errno': 4001,
#                     'errmsg': '数据库查询错误'
#                 })
#
#         # 返回整理好的地区数据
#         return JsonResponse({
#             'errmsg': '获取成功',
#             'errno': '0',
#             'date': areas_list
#         })


# class AvatarView(View):
#
#     def post(self, request):
#         pass


class AuthView(LoginMixin, View):
    '''实名认证'''

    def post(self, request):
        # 获取前端数据
        json_dict = json.loads(request.body)
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')
        # 检验参数是否完整
        if not all([real_name, id_card]):
            return JsonResponse({
                'errno': '4002',
                'errmsg': '缺少参数'
            })

        # 判断身份证号是否重复
        try:
            user_check = User.objects.filter(id_card=id_card)
            if user_check:
                return JsonResponse({
                    'errno': '4003',
                    'errmsg': '身份证号已存在'
                })
        except Exception as e:
            return JsonResponse({
                'errno': '4001',
                'errmsg': '数据库查询出错'
            })

        # 验证身份证号是否合规
        result = check(id_card)

        user = request.user
        # 如果合规，往数据库里保存数据
        if result:
            try:
                user.real_name = real_name
                user.id_card = id_card
                user.save()
            # 数据库储存数据失败
            except Exception as e:
                return JsonResponse({
                    'errno': '4001',
                    'errmsg': '数据库存储失败'
                })
            # 数据库储存数据成功
            else:
                return JsonResponse({
                    'errno': '0',
                    'errmsg': '认证信息保存成功',
                    'data': {
                        'real_name': real_name,
                        'id_card': id_card
                    }
                })
        # 身份证号不合规
        return JsonResponse({
            'errno': '4004',
            'errmsg': '身份信息认证失败'
        })

    def get(self, request):
        # 获取用户信息
        real_name = request.user.real_name
        id_card = request.user.id_card

        # 返回用户信息
        return JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': {'real_name': real_name,
                     'id_card': id_card}
        })


class HouseDetailView(View):
    '''房屋详情页'''

    def get(self, request, house_id):

        user = request.user
        # 判断用户是否登录
        if not user.is_authenticated:
            user_id = -1
        else:
            user_id = user.id

        # 从数据库获取房屋图片
        try:
            house = House.objects.get(id=house_id)
            url_list = HouseImage.objects.filter(house_id=house_id)
        except Exception as e:
            return JsonResponse({
                'errno': '4004',
                'errmsg': '查询数据库失败'
            })

        # 添加房屋图片列表信息
        image_list = []
        for index_image_url in url_list:
            image_list.append(index_image_url.url)

        # 获取房屋评论
        orders = Order.objects.filter(house_id=house_id)
        comments = []
        for order in orders:
            comments.append({
                'comment': order.comment,
                'ctime': order.create_time,
                'user_name': user_id
            })

        # 获取房屋设施信息
        house = House.objects.get(id=house_id)
        facilities = house.facility.all()
        facility_list = []
        for value in facilities:
            facility_list.append(value.id)

        return JsonResponse({
            "data": {
                "house": {
                    "acreage": house.acreage,
                    "address": house.address,
                    "beds": house.beds,
                    "capacity": house.capacity,
                    "comments": comments,
                    "deposit": house.deposit,
                    "facilities": facility_list,
                    "hid": house_id,
                    "img_urls": image_list,
                    "max_days": house.max_days,
                    "min_days": house.min_days,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "unit": house.unit,
                    "user_avatar": "http://127.0.0.1:8888/" + str(house.user.avatar),
                    "user_id": house.user.id,
                    "user_name": house.user.real_name
                },
                "user_id": user_id
            },
            "errmsg": "OK",
            "errno": "0"
        })
